package kr.co.bettersoft.pushchat.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import kr.co.bettersoft.pushchat.activity.DiaryDetailActivity;
import kr.co.bettersoft.pushchat.activity.DiaryWriteActivity;
import kr.co.bettersoft.pushchat.activity.MemberInfoActivity;
import kr.co.bettersoft.pushchat.activity.PullToRefreshListView;
import kr.co.bettersoft.pushchat.activity.R;
import kr.co.bettersoft.pushchat.activity.PullToRefreshListView.OnRefreshListener;
import kr.co.bettersoft.pushchat.adapter.PushChatDiaryListAdapter;
import kr.co.bettersoft.pushchat.adapter.PushChatFriendListAdapter;
import kr.co.bettersoft.pushchat.adapter.PushChatMemberListAdapter;
import kr.co.bettersoft.pushchat.common.CommonConstant;
import kr.co.bettersoft.pushchat.common.CommonUtil;
import kr.co.bettersoft.pushchat.common.PushChatRest;
import kr.co.bettersoft.pushchat.common.SwipeListViewFragment;
import kr.co.bettersoft.pushchat.domain.PushChatDiary;
import kr.co.bettersoft.pushchat.domain.PushChatFriend;
import kr.co.bettersoft.pushchat.domain.PushChatMember;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * DiaryListFragment
 *  일기 리스트 프래그먼트
 *   상단 타이틀 : 일기 / 좌측에 내 일기 버튼 / 우측에 일기 검색 버튼
 *   리스트 - 일기 섬네일 이미지,  일기 제목, 글쓴이, 등록 시간, 좋아요 수
 *   
 *   내 일기 버튼 누르면 자체 화면 변환.
 *     타이틀 : 내 일기. / 좌측 전체 일기 버튼 / 우측 쓰기 버튼
 *     내 일기 리스트 나오는 건 전체 일기 리스트와 동일하나, 내 일기만 소팅해서 보여줌. 
 *  
 * @author blue
 *
 */
public class DiaryListFragment extends SwipeListViewFragment{			
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 변수

	String TAG = "DiaryListFragment";

	// 구현할 기능. 일기 목록 - 나와 친구들의 일기 목록  // 검색 시 검색 조건 받아와서 일기 목록.  메소드가 같으므로 한번 구현으로. 화면 방식은 멤버 목록과 동일.
	// 내 일기 목록 - 내가 쓴 일기 목록

	public final int SELECT_MY_DIARY_LIST = 101;  		// 내가 쓴 다이어리 목록을 가져온다.		// selectMyDiaryList
	public final int SELECT_SEARCH_DIARY_LIST = 102;    // 다이어리 목록을 가져온다. 조건을 넣으면 조건검색 가능.  	// selectSearchDiaryList
	public final int UPDATE_DEACTIVATE_DIARY = 103;    // 일기를 비활성화한다		updateDeactivateDiary



	SharedPreferences sharedPrefCustom;	// 공용 프립스	
	String userId;						// 사용자 아이디

	// 프래그먼트 종료 여부. 종료된 경우 스레드 호출로 인한 에러를 방지하기 위함
	Boolean isFinished = false;

	//		Boolean entranceMode = false;

	// 서버 통신용
	static Boolean countOne = true;		// 한번에 한번만 통신 하도록
	PushChatRest pushChatRest;
	String callResult = "";
	JSONObject jsonObject;

	String resultStr;		// 요청 결과
	//		Boolean tmpFirstItem = true;		// 첫 아이템만 백그라운드 효과


	// 서버에서 받은 대기 인원 리스트 임시 저장
	int max = 0;

	// 검색용 - 다이어리 검색 아직 미구현.
	PushChatMember pushChatMemberParam;
	PushChatDiary pushChatDiaryParamForSearch;
	Boolean isSearchMode = false;

	// 전체 일기 리스트
	List<PushChatDiary> pushChatDiaryEntriesFn;
	// 내 일기 리스트
	List<PushChatDiary> pushChatMyDiaryEntriesFn;

	// 삭제 - 취소 포지션
	public int cancelPosition;
	boolean needScroll = false;
	// adapter
	private PushChatDiaryListAdapter pushChatDiaryListAdapter;
	private PushChatDiaryListAdapter pushChatMyDiaryListAdapter;

	// 화면 구성

	View mainDiarylistTitle_1;
	View mainDiarylistTitle_2;

	ImageButton mainDiaryListMyDiaryListBtn;		// 상단 내 일기 목록보기 버튼
	Button mainDiaryListDiaryListBtn;		// 상단 일기 목록보기 버튼
	ImageButton mainDiaryListDiarySearchBtn;		// 상단 일기 검색 버튼
	ImageButton mainDiaryListDiaryWriteBtn;		// 상단 일기 쓰기 버튼

	ListView diaryListView;
	View emptyView;				// 데이터 없음 뷰
	ProgressBar pb1;		// 중단 로딩 진행바

	// pull down refresh
	Boolean pullDownRefreshIng  = false;

	int screenMode = 3;		// 상세 화면 보는지 여부. 상세화면 보고 온 경우에는 리스트를 갱신해준다?		// screenMode 1 : 전체 목록. 2 : 내일기목록. 3 전체목록. refresh필요. 4. 내일기목록. refresh 필요


	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		

				if(b.getInt("showToast")==1){		// 화면에 토스트 띄우기
					Toast.makeText(getActivity(), b.getString("msg"), Toast.LENGTH_SHORT).show();
				}
				if(b.getInt("showAlert")==1){					 // 경고창 . 
					//
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant. alertTitle )                                        
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 단순 확인 용도
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("showDiaryList")==1){
					// 데이터를 화면에.. 
					if((pushChatDiaryEntriesFn!=null)&&(pushChatDiaryEntriesFn.size()>0)){
						setGriding();			// 항시 업뎃
						diaryListView.setVisibility(View.VISIBLE);
						emptyView.setVisibility(View.GONE);
					}else{
						Log.d(TAG,"no data");
						diaryListView.setEmptyView(emptyView);
						diaryListView.setVisibility(View.GONE);
						emptyView.setVisibility(View.VISIBLE);
					}
				}
				if(b.getInt("showMyDiaryList")==1){
					// 데이터를 화면에.. 
					if((pushChatMyDiaryEntriesFn!=null)&&(pushChatMyDiaryEntriesFn.size()>0)){
						setGriding2();			// 항시 업뎃
						diaryListView.setVisibility(View.VISIBLE);
						emptyView.setVisibility(View.GONE);
					}else{
						Log.d(TAG,"no data");
						diaryListView.setEmptyView(emptyView);
						diaryListView.setVisibility(View.GONE);
						emptyView.setVisibility(View.VISIBLE);
					}
				}

				if(b.getInt("confirmAndDelete")==1){					 // 확인받고 대기 취소.
					// 뷰를 보여주도록 하고, 버튼 클릭시 호출 되도록 하기.
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant. alertTitle )                                        
					.setMessage(getResources().getString(R.string.delete_confirm))	// 확인 질문
					.setIcon(R.drawable.ic_dialog_img)		
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							handler.sendEmptyMessage(UPDATE_DEACTIVATE_DIARY);	//삭제 - 컨트롤러에서 처리
						}})
						.setNegativeButton(android.R.string.no, null).show();
				}

				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.GONE);
				}
				switch (msg.what)
				{
				case SELECT_MY_DIARY_LIST : 			// 내가 쓴 다이어리 목록을 가져온다.		// selectMyDiaryList
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableSelectMyDiaryList());
					}
					break;
				case SELECT_SEARCH_DIARY_LIST : 		// 다이어리 목록을 가져온다. 조건을 넣으면 조건검색 가능.  	// selectSearchDiaryList
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableSelectSearchDiaryList());
					}
					break;	
				case UPDATE_DEACTIVATE_DIARY : 		// 일기를 비활성화한다  	// updateDeactivateDiary
					if(getActivity()!=null) {
						getActivity().runOnUiThread(new RunnableUpdateDeactivateDiary());
					}
					break;	
				default : 
					break;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	/**
	 * setGriding
	 * 데이터를 화면에 세팅한다 - 일기 목록
	 *
	 * @param 
	 * @param 
	 * @return 
	 */
	public void setGriding(){
		pushChatDiaryListAdapter = new PushChatDiaryListAdapter(getActivity(), this, pushChatDiaryEntriesFn);
		diaryListView.setAdapter(pushChatDiaryListAdapter);

		//			// 클릭시 상세보기 페이지로
		//			diaryListView.setOnItemClickListener(new OnItemClickListener() {
		//				public void onItemClick(AdapterView<?> parent, View v,
		//						int position, long id) {
		//					
		////					// screenMode 1 : 전체 목록. 2 : 내일기목록. 3 전체목록. refresh필요. 4. 내일기목록. refresh 필요
		////					if(screenMode==1){
		//						screenMode = 3;
		////					}else if(screenMode==2){
		////						screenMode = 4;
		////					}
		//					Intent intent = new Intent(getActivity(), DiaryDetailActivity.class);
		//					PushChatDiary pushChatDiaryParam =  pushChatDiaryEntriesFn.get(position);
		//					intent.putExtra("idPushChatDiary", pushChatDiaryParam.getIdPushChatDiary());	
		//					intent.putExtra("writerId", pushChatDiaryParam.getMemberId());	
		//					//
		//					startActivity(intent);
		//				}	
		//			});

		//			// item 롱클릭시 
		//			diaryListView.setOnItemLongClickListener(new OnItemLongClickListener() {
		//				@Override
		//				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
		//						int arg2, long arg3) {
		//					if(diaryListView.getCount()==pushChatMemberEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
		////						firstEntrancePosition = arg2;
		//					}else{
		////						firstEntrancePosition = arg2 -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
		//					}
		//					return false;
		//				}
		//			});
	}

	/**
	 * setGriding2
	 * 데이터를 화면에 세팅한다 - 내일기 목록
	 *
	 * @param 
	 * @param 
	 * @return 
	 */
	public void setGriding2(){
		pushChatMyDiaryListAdapter = new PushChatDiaryListAdapter(getActivity(), this, pushChatMyDiaryEntriesFn);
		diaryListView.setAdapter(pushChatMyDiaryListAdapter);

		//			// 클릭시 상세보기 페이지로
		//			diaryListView.setOnItemClickListener(new OnItemClickListener() {
		//				public void onItemClick(AdapterView<?> parent, View v,
		//						int position, long id) {
		//						screenMode = 2;
		//					Intent intent = new Intent(getActivity(), DiaryDetailActivity.class);
		//					PushChatDiary pushChatDiaryParam =  pushChatMyDiaryEntriesFn.get(position);
		//					intent.putExtra("idPushChatDiary", pushChatDiaryParam.getIdPushChatDiary());							//
		//					startActivity(intent);
		//				}	
		//			});

		if(needScroll){
			needScroll = false;
			if(cancelPosition>3){
				diaryListView.setSelection(cancelPosition-1);
			}
		}
	}
	//		
	//		
	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public ListView getListView() {
		return diaryListView;
	}

	@Override
	public void getSwipeItem(boolean isRight, int position) {
		if(screenMode == 1 || screenMode == 3){		// 전체 일기 - > 무시한다.
			//				if(diaryListView.getCount()==pushChatDiaryEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
			//					cancelPosition = position;
			//				}else{
			//					cancelPosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
			//				}
			//				// 밀면 우측 숨겨진 버튼이 보이도록 하기.
			//				if(isRight){		// 오른쪽으로 밀면 숨김
			//					pushChatDiaryEntriesFn.get(cancelPosition).setShowCancelBtnYn(false);
			//				}else{				// 왼쪽으로 밀면 생김
			//					pushChatDiaryEntriesFn.get(cancelPosition).setShowCancelBtnYn(true);
			//				}
			//				pushChatDiaryListAdapter.notifyDataSetChanged();
		}else if(screenMode == 2 || screenMode == 4){		// 내 일기만 삭제 되도록 한다.
			if(diaryListView.getCount()==pushChatMyDiaryEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
				cancelPosition = position;
			}else{
				cancelPosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
			}
			// 밀면 우측 숨겨진 버튼이 보이도록 하기.
			if(isRight){		// 오른쪽으로 밀면 숨김
				pushChatMyDiaryEntriesFn.get(cancelPosition).setShowCancelBtnYn(false);
			}else{				// 왼쪽으로 밀면 생김
				pushChatMyDiaryEntriesFn.get(cancelPosition).setShowCancelBtnYn(true);
			}
			pushChatMyDiaryListAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onItemClickListener(ListAdapter adapter, int position) {


		int diaryRealPosition = 0;

		if(screenMode==1 || screenMode==3){
			if(diaryListView.getCount()==pushChatDiaryEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
				diaryRealPosition = position;
			}else{
				diaryRealPosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
			}
			screenMode = 3;
			Intent intent = new Intent(getActivity(), DiaryDetailActivity.class);
			PushChatDiary pushChatDiaryParam =  pushChatDiaryEntriesFn.get(diaryRealPosition);
			intent.putExtra("idPushChatDiary", pushChatDiaryParam.getIdPushChatDiary());	
			intent.putExtra("writerId", pushChatDiaryParam.getMemberId());	
			startActivity(intent);
		}else if(screenMode==2 || screenMode==4){
			if(diaryListView.getCount()==pushChatMyDiaryEntriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
				diaryRealPosition = position;
			}else{
				diaryRealPosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
			}
			screenMode = 4;
			Intent intent = new Intent(getActivity(), DiaryDetailActivity.class);
			PushChatDiary pushChatDiaryParam =  pushChatMyDiaryEntriesFn.get(diaryRealPosition);
			intent.putExtra("idPushChatDiary", pushChatDiaryParam.getIdPushChatDiary());							//
			intent.putExtra("writerId", pushChatDiaryParam.getMemberId());	
			startActivity(intent);
		}
	}
	@Override
	public void onItemLongClickListener(ListAdapter adapter, int position) {
		//			if(diaryListView.getCount()==entriesFn.size()){	// 상단에 아무것도 없으므로 그냥 사용
		//				firstEntrancePosition = position;
		//			}else{
		//				firstEntrancePosition = position -1;		// 상단에 pull down refresh 영역 한칸 차지하고 있으므로 한칸 빼줌.
		//			}
		//			if(firstEntrancePosition!=0){		// 0 번째는 우선 입장 기능 x. 일반 입장o
		//				confirmAndEnterUser2();
		//			}else{
		//				confirmAndEnterUser();			// 0번째에게는 일반 입장창이라도 뜨게 함. (0번째만 안뜨니 이상해서)
		//			}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_diarylist, null);

		pushChatRest = new PushChatRest();

		mainDiarylistTitle_1 = (View) view.findViewById(R.id.main_diarylist_title_1);	
		mainDiarylistTitle_2 = (View) view.findViewById(R.id.main_diarylist_title_2);	

		mainDiaryListMyDiaryListBtn = (ImageButton) view.findViewById(R.id.main_diarylist_friendlist_btn);
		mainDiaryListDiaryListBtn = (Button) view.findViewById(R.id.main_diarylist_diarylist_btn);
		mainDiaryListDiarySearchBtn = (ImageButton) view.findViewById(R.id.main_diarylist_diarysearch_btn);
		mainDiaryListDiaryWriteBtn = (ImageButton) view.findViewById(R.id.main_diarylist_diarywrite_btn);

		diaryListView = (ListView) view.findViewById(R.id.diary_list_view);		
		emptyView = view.findViewById(R.id.empty1);		// 데이터 없으면 '빈 페이지'(데이터 없음 메시지)표시
		pb1=(ProgressBar) view.findViewById(R.id.main_progressbar);

		//			// 사용자 아이디를 꺼낸다.
		sharedPrefCustom = getActivity().getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		userId = sharedPrefCustom.getString("userId", "");
		//			
		// 버튼 리스너
		mainDiaryListMyDiaryListBtn.setOnClickListener(new OnClickListener() {		// 내 일기 버튼
			@Override
			public void onClick(View v) {
				Log.d(TAG,"mainDiaryListMyDiaryListBtn click");
				mainDiarylistTitle_1.setVisibility(View.GONE);
				mainDiarylistTitle_2.setVisibility(View.VISIBLE);
				handler.sendEmptyMessage(SELECT_MY_DIARY_LIST);
			}
		});
		mainDiaryListDiaryListBtn.setOnClickListener(new OnClickListener() {		// 전체 일기 목록 버튼
			@Override
			public void onClick(View v) {
				Log.d(TAG,"mainDiaryListDiaryListBtn click");
				mainDiarylistTitle_2.setVisibility(View.GONE);
				mainDiarylistTitle_1.setVisibility(View.VISIBLE);
				handler.sendEmptyMessage(SELECT_SEARCH_DIARY_LIST);
			}
		});
		mainDiaryListDiarySearchBtn.setOnClickListener(new OnClickListener() {		// 일기 검색 버튼
			@Override
			public void onClick(View v) {
				Log.d(TAG,"mainDiaryListDiarySearchBtn click");
				// ### 일기 startActivityForResult ...
			}
		});
		mainDiaryListDiaryWriteBtn.setOnClickListener(new OnClickListener() {		// 일기 쓰기 버튼
			@Override
			public void onClick(View v) {
				Log.d(TAG,"mainDiaryListDiaryWriteBtn click");
				screenMode = 4;
				// ### 일기 쓰기 startActivity
				Intent intent = new Intent(getActivity(), DiaryWriteActivity.class);
				//					PushChatMember pushChatMemberParam =  pushChatMemberEntriesFn.get(position);
				//					intent.putExtra("memberId", pushChatMemberParam.getMemberId());							//
				startActivity(intent);
			}
		});


		////////////////////////////////pull down list
		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) diaryListView).setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// Do work to refresh the list here.
				if(countOne){
					countOne = false;		
					try {
						pullDownRefreshIng = true;				// 기본 로딩바는 보여주지 않기 위함
						new GetDataTask().execute();
					}catch (Exception e) {
						e.printStackTrace();
					} 
				}else{
					Log.d(TAG,"already running..");		 
					((PullToRefreshListView) diaryListView).onRefreshComplete();
				}

			}
		});


		return view;
	}
	//
	//	//////////////////////////////////////////////////////////////////////////////////////////////////////
	// pull down list

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {
		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			Log.d(TAG,"GetDataTask");

			if(screenMode==1 || screenMode==3){
				screenMode = 1;
				// 파라미터 세팅
				PushChatDiary pushChatDiaryParam = new PushChatDiary();
				pushChatDiaryParam.setNickName("");		
				pushChatDiaryParam.setCategory("");		
				pushChatDiaryParam.setSubject("");
				pushChatDiaryParam.setContent("");
				// 서버 메소드 호출
				if(!isFinished){
					callResult = pushChatRest.RestSelectSearchDiaryList(pushChatDiaryParam, returnThis());
					// 결과 처리
					if(!(callResult.equals("F"))){
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							pushChatDiaryEntriesFn = new ArrayList<PushChatDiary>(max);
							//
							Date tempDate = new Date();
							String tmp_idPushChatDiary = "";
							String tmp_memberId = "";
							String tmp_nickName = "";
							String tmp_subject = "";
							String tmp_content = "";
							String tmp_fileUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_modifyDate = "";
							String tmp_registerDate = "";
							String tmp_likeCount = "";
							Bitmap tmp_thumbnail = null;
							Bitmap tmp_file = null;
							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idPushChatDiary = jsonObj.getString("idPushChatDiary");
									}catch(Exception e){
										tmp_idPushChatDiary = "";
									}
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_subject = jsonObj.getString("subject");
									}catch(Exception e){
										tmp_subject = "";
									}
									try{
										tmp_content = jsonObj.getString("content");
									}catch(Exception e){
										tmp_content = "";
									}
									try{
										tmp_modifyDate = jsonObj.getString("modifyDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_modifyDate);
										//											commonUtil.context = context;

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_modifyDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_modifyDate = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_registerDate);

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_registerDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_likeCount = jsonObj.getString("likeCount");
									}catch(Exception e){
										tmp_likeCount = "";
									}
									try{
										tmp_fileUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_fileUrl==null||tmp_fileUrl.length()<1||tmp_fileUrl.equals("null")){
											tmp_file = null;
										}else{
											tmp_file = LoadImage(tmp_fileUrl);
										}
									}catch(Exception e){
										tmp_fileUrl = "";
										tmp_file = null;
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl==null||tmp_thumbnailUrl.length()<1||tmp_thumbnailUrl.equals("null")){
											tmp_thumbnail = null;
										}else{
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
										tmp_thumbnail = null;
									}

									pushChatDiaryEntriesFn.add(new PushChatDiary(
											tmp_idPushChatDiary,
											tmp_memberId,
											tmp_nickName,
											tmp_subject,
											tmp_content,
											tmp_fileUrl,
											tmp_thumbnailUrl,
											tmp_modifyDate,
											tmp_registerDate,
											tmp_likeCount,
											tmp_thumbnail,
											tmp_file
									));
								}
							}
						}catch (Exception e) {
							e.printStackTrace();
						}
					}
					showDiaryList();
				}
			}else if(screenMode==2 || screenMode==4){
				screenMode = 2;
				// 파라미터 세팅
				PushChatDiary pushChatDiaryParam = new PushChatDiary();
				pushChatDiaryParam.setMemberId(userId);
				//					Log.d(TAG,"userId:"+userId);
				// 서버 메소드 호출
				if(!isFinished){
					callResult = pushChatRest.RestSelectMyDiaryList(pushChatDiaryParam, returnThis());
					// 결과 처리
					if(!(callResult.equals("F"))){
						//							pushChatMyDiaryEntriesFn = pushChatRest.getPushChatDiaryEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							//			Log.d(TAG,"max:"+max);
							pushChatMyDiaryEntriesFn = new ArrayList<PushChatDiary>(max);

							Date tempDate = new Date();

							String tmp_idPushChatDiary = "";
							String tmp_memberId = "";
							String tmp_nickName = "";
							String tmp_subject = "";
							String tmp_content = "";
							String tmp_fileUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_modifyDate = "";
							String tmp_registerDate = "";
							String tmp_likeCount = "";

							Bitmap tmp_thumbnail = null;
							Bitmap tmp_file = null;
							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idPushChatDiary = jsonObj.getString("idPushChatDiary");
									}catch(Exception e){
										tmp_idPushChatDiary = "";
									}
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_subject = jsonObj.getString("subject");
									}catch(Exception e){
										tmp_subject = "";
									}
									try{
										tmp_content = jsonObj.getString("content");
									}catch(Exception e){
										tmp_content = "";
									}
									try{
										tmp_modifyDate = jsonObj.getString("modifyDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_modifyDate);

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_modifyDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_modifyDate = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_registerDate);

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										tmp_registerDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_likeCount = jsonObj.getString("likeCount");
									}catch(Exception e){
										tmp_likeCount = "";
									}
									try{
										tmp_fileUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_fileUrl==null||tmp_fileUrl.length()<1||tmp_fileUrl.equals("null")){
											tmp_file = null;
										}else{
											tmp_file = LoadImage(tmp_fileUrl);
										}
									}catch(Exception e){
										tmp_fileUrl = "";
										tmp_file = null;
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl==null||tmp_thumbnailUrl.length()<1||tmp_thumbnailUrl.equals("null")){
											tmp_thumbnail = null;
										}else{
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
										tmp_thumbnail = null;
									}

									pushChatMyDiaryEntriesFn.add(new PushChatDiary(
											tmp_idPushChatDiary,
											tmp_memberId,
											tmp_nickName,
											tmp_subject,
											tmp_content,
											tmp_fileUrl,
											tmp_thumbnailUrl,
											tmp_modifyDate,
											tmp_registerDate,
											tmp_likeCount,
											tmp_thumbnail,
											tmp_file
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
				showMyDiaryList();
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null;
		}
		@Override
		protected void onPostExecute(String[] result) {
			// Call onRefreshComplete when the list has been refreshed.
			pullDownRefreshIng = false;							// 기본 로딩바 보여주기 상태 초기화. resume 기능으로는 보여지도록.
			((PullToRefreshListView) diaryListView).onRefreshComplete();		// 리프레시가 끝났음을....
			super.onPostExecute(result);
		}
	}


	//	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//	// 자체 사용 메소드


	/**
	 * Diary 리스트를 보여준다
	 * showDiaryList
	 */
	public void showDiaryList(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showDiaryList", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	/**
	 * 내 일기 리스트를 보여준다
	 * showMyDiaryList
	 */
	public void showMyDiaryList(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showMyDiaryList", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * confirmAndDelete
	 *  확인 후 삭제
	 *
	 * @param msg
	 * @param
	 * @return 
	 */
	public void confirmAndDelete(){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("confirmAndDelete", 1);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


	/**
	 * 러너블. 내가 쓴 다이어리 목록을 가져온다.	
	 */
	class RunnableSelectMyDiaryList implements Runnable {
		public void run(){
			new backgroundThreadSelectMyDiaryList().execute();
		}
	}
	/**
	 * backgroundThreadSelectMyDiaryList
	 * 비동기 스레드 내가 쓴 다이어리 목록을 가져온다.	
	 * @author blue
	 *
	 */
	public class backgroundThreadSelectMyDiaryList extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadSelectMyDiaryList");

			screenMode = 2;
			// 파라미터 세팅
			PushChatDiary pushChatDiaryParam = new PushChatDiary();
			pushChatDiaryParam.setMemberId(userId);
			Log.d(TAG,"userId:"+userId);
			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestSelectMyDiaryList(pushChatDiaryParam, returnThis());
					// 결과 처리
					if(!(callResult.equals("F"))){
						//							pushChatMyDiaryEntriesFn = pushChatRest.getPushChatDiaryEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							//			Log.d(TAG,"max:"+max);
							pushChatMyDiaryEntriesFn = new ArrayList<PushChatDiary>(max);

							Date tempDate = new Date();

							String tmp_idPushChatDiary = "";
							String tmp_memberId = "";
							String tmp_nickName = "";
							String tmp_subject = "";
							String tmp_content = "";
							String tmp_fileUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_modifyDate = "";
							String tmp_registerDate = "";
							String tmp_likeCount = "";

							Bitmap tmp_thumbnail = null;
							Bitmap tmp_file = null;
							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idPushChatDiary = jsonObj.getString("idPushChatDiary");
									}catch(Exception e){
										tmp_idPushChatDiary = "";
									}
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_subject = jsonObj.getString("subject");
									}catch(Exception e){
										tmp_subject = "";
									}
									try{
										tmp_content = jsonObj.getString("content");
									}catch(Exception e){
										tmp_content = "";
									}
									try{
										tmp_modifyDate = jsonObj.getString("modifyDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_modifyDate);
										//											commonUtil.context = context;

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_modifyDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_modifyDate = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_registerDate);

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										tmp_registerDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_likeCount = jsonObj.getString("likeCount");
									}catch(Exception e){
										tmp_likeCount = "";
									}
									try{
										tmp_fileUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_fileUrl==null||tmp_fileUrl.length()<1||tmp_fileUrl.equals("null")){
											tmp_file = null;
											//								tmp_thumbnail = getResoucres().getDrawable(R.drawable.ic_launcher);
										}else{
											//								Log.d(TAG,i+"//tmp_fileUrl::"+tmp_fileUrl);
											//								tmp_thumbnail = null;
											tmp_file = LoadImage(tmp_fileUrl);
										}
									}catch(Exception e){
										tmp_fileUrl = "";
										tmp_file = null;
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl==null||tmp_thumbnailUrl.length()<1||tmp_thumbnailUrl.equals("null")){
											tmp_thumbnail = null;
										}else{
											//								Log.d(TAG,i+"//tmp_thumbnailUrl::"+tmp_thumbnailUrl);
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
										tmp_thumbnail = null;
									}

									pushChatMyDiaryEntriesFn.add(new PushChatDiary(
											tmp_idPushChatDiary,
											tmp_memberId,
											tmp_nickName,
											tmp_subject,
											tmp_content,
											tmp_fileUrl,
											tmp_thumbnailUrl,
											tmp_modifyDate,
											tmp_registerDate,
											tmp_likeCount,
											tmp_thumbnail,
											tmp_file
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
						//							pushChatDiaryEntriesFn = pushChatDiaryEntries; 
					}
					showMyDiaryList();
				}
				hidePb();		// @@ 
				FragmentHome.restCallCntDown();
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null; 
		}
	}


	/**
	 * 러너블. 다이어리 목록을 가져온다. 조건을 넣으면 조건검색 가능.
	 */
	class RunnableSelectSearchDiaryList implements Runnable {		
		public void run(){
			new backgroundThreadSelectSearchDiaryList().execute();
		}
	}
	/**
	 * backgroundThreadSelectSearchDiaryList
	 * 비동기 스레드  다이어리 목록을 가져온다. 조건을 넣으면 조건검색 가능.
	 * @author blue
	 *
	 */
	public class backgroundThreadSelectSearchDiaryList extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadSelectSearchDiaryList");
			screenMode = 1;
			// 파라미터 세팅
			PushChatDiary pushChatDiaryParam = new PushChatDiary();
			// 검색 조건 있을때
			if(isSearchMode){
				pushChatDiaryParam.setNickName(pushChatDiaryParamForSearch.getNickName());		
				pushChatDiaryParam.setCategory(pushChatDiaryParamForSearch.getCategory());		
				pushChatDiaryParam.setSubject(pushChatDiaryParamForSearch.getSubject());
				pushChatDiaryParam.setContent(pushChatDiaryParamForSearch.getContent());
			}else{
				pushChatDiaryParam.setNickName("");		
				pushChatDiaryParam.setCategory("");		
				pushChatDiaryParam.setSubject("");
				pushChatDiaryParam.setContent("");
			}
			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestSelectSearchDiaryList(pushChatDiaryParam, returnThis());
					// 결과 처리
					if(!(callResult.equals("F"))){

						//							pushChatDiaryEntriesFn = pushChatRest.getPushChatDiaryEntriesFn();
						try {
							JSONArray jsonArray = new JSONArray(callResult);
							int max = jsonArray.length();
							//			Log.d(TAG,"max:"+max);
							pushChatDiaryEntriesFn = new ArrayList<PushChatDiary>(max);

							/*
							 * {"idPushChatDiary":"7",							// ** 상세 정보 조회에 필요하므로 필수 저장.
							 * "memberId":"a@a.a",								// ? 상세정보에서 사용함.
							 * "nickName":"김준우",								// * 글쓴이
							 * "subject":"귀요미 시연이",							// * 제목
							 * "content":"그런데 포도는 별로 좋아하지 않는 모양..\n뱉어버리네. \n흠냐. \n",
							 * "fileUrl":"http://www.onemobileservice.com/pushchat/diary-upload-image/a@a.a_201309061325387.png",			// ? 상세정보에서 사용함
							 * "thumbnailUrl":"http://www.onemobileservice.com/pushchat/diary-upload-thumbnail/a@a.a_201309061325387.png",	// * 목록에선 썸네일이..
							 * "modifyDate":"2013-09-06 13:25:06",				// * 수정기능 있으니 일단 둘다 저장
							 * "registerDate":"2013-09-06 13:25:06",			// *
							 * "likeCount":"2"},								// * 좋아요 숫자
							 */

							Date tempDate = new Date();

							String tmp_idPushChatDiary = "";
							String tmp_memberId = "";
							String tmp_nickName = "";
							String tmp_subject = "";
							String tmp_content = "";
							String tmp_fileUrl = "";
							String tmp_thumbnailUrl = "";
							String tmp_modifyDate = "";
							String tmp_registerDate = "";
							String tmp_likeCount = "";
							//					Bitmap tmp_profileImage = null;
							Bitmap tmp_thumbnail = null;
							Bitmap tmp_file = null;
							if(max>0){
								for ( int i = 0; i < max; i++ ){
									JSONObject jsonObj = jsonArray.getJSONObject(i);
									try{
										tmp_idPushChatDiary = jsonObj.getString("idPushChatDiary");
									}catch(Exception e){
										tmp_idPushChatDiary = "";
									}
									try{
										tmp_memberId = jsonObj.getString("memberId");
									}catch(Exception e){
										tmp_memberId = "";
									}
									try{
										tmp_nickName = jsonObj.getString("nickName");
									}catch(Exception e){
										tmp_nickName = "";
									}
									try{
										tmp_subject = jsonObj.getString("subject");
									}catch(Exception e){
										tmp_subject = "";
									}
									try{
										tmp_content = jsonObj.getString("content");
									}catch(Exception e){
										tmp_content = "";
									}
									try{
										tmp_modifyDate = jsonObj.getString("modifyDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_modifyDate);
										//											commonUtil.context = context;

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_modifyDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_modifyDate = "";
									}
									try{
										tmp_registerDate = jsonObj.getString("registerDate");
										// 형변환 작업
										CommonUtil commonUtil = new CommonUtil();
										tempDate = commonUtil.sf.parse(tmp_registerDate);

										String year = getString(R.string.year);
										String month = getString(R.string.month);
										String day = getString(R.string.day);
										String hour = getString(R.string.hour);
										String minute = getString(R.string.minute);
										SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
										SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
										SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

										tmp_registerDate = sfGeneral.format(tempDate);
									}catch(Exception e){
										tmp_registerDate = "";
									}
									try{
										tmp_likeCount = jsonObj.getString("likeCount");
									}catch(Exception e){
										tmp_likeCount = "";
									}
									try{
										tmp_fileUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_fileUrl==null||tmp_fileUrl.length()<1||tmp_fileUrl.equals("null")){
											tmp_file = null;
											//								tmp_thumbnail = getResoucres().getDrawable(R.drawable.ic_launcher);
										}else{
											//								Log.d(TAG,i+"//tmp_fileUrl::"+tmp_fileUrl);
											//								tmp_thumbnail = null;
											tmp_file = LoadImage(tmp_fileUrl);
										}
									}catch(Exception e){
										tmp_fileUrl = "";
										tmp_file = null;
									}
									try{
										tmp_thumbnailUrl = jsonObj.getString("thumbnailUrl");
										if(tmp_thumbnailUrl==null||tmp_thumbnailUrl.length()<1||tmp_thumbnailUrl.equals("null")){
											tmp_thumbnail = null;
											//								tmp_thumbnail = getResoucres().getDrawable(R.drawable.ic_launcher);
										}else{
											//								Log.d(TAG,i+"//tmp_thumbnailUrl::"+tmp_thumbnailUrl);
											//								tmp_thumbnail = null;
											tmp_thumbnail = LoadImage(tmp_thumbnailUrl);
										}
									}catch(Exception e){
										tmp_thumbnailUrl = "";
										tmp_thumbnail = null;
									}


									pushChatDiaryEntriesFn.add(new PushChatDiary(
											tmp_idPushChatDiary,
											tmp_memberId,
											tmp_nickName,
											tmp_subject,
											tmp_content,
											tmp_fileUrl,
											tmp_thumbnailUrl,
											tmp_modifyDate,
											tmp_registerDate,
											tmp_likeCount,
											tmp_thumbnail,
											tmp_file
									));
								}
							}
						}catch (JSONException e) {
							e.printStackTrace();
						}
						//							pushChatDiaryEntriesFn = pushChatDiaryEntries; 

						//			try {
						//				jsonObject = new JSONObject(tempstr);		// list diary
						//				callResult = "";
						//				try{
						//					callResult = jsonObject.getString("totalCount");
						//				}catch(Exception e){
						//					callResult = "0";
						//				}
						//			} catch (JSONException e) {
						//				callResult = "0";
						//			}



						//							tempstr = pushChatRest.getTempstr();
						//							try {
						//								// 데이터 세팅부..
						//								jsonObject = new JSONObject(tempstr);
						//								try{
						//									totalCount = jsonObject.getString("totalCount");
						//									if(totalCount==null || totalCount.equals("null")){
						//										totalCount = "0";
						//									}
						//								}catch(Exception e){
						//									totalCount = "0";
						//								}
						//								showWaitNum();
						//							} catch (JSONException e) {
						//								e.printStackTrace();
						//							} 
					}
					showDiaryList();
				}
				hidePb();		// @@ 
				FragmentHome.restCallCntDown();
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			//				if(totalCount==null || totalCount.equals("null")){
			//					Log.d(TAG,"totalCount==null");
			//					totalCount = "0";
			//				}
			//				if(!totalCount.equals("0")){
			//					// --> 바로 대기 리스트 가져온다.
			//					handler.sendEmptyMessage(GET_WAIT_LIST);		// (현재 대기인원 구하고 나서 자동) 
			//				}else{
			//					entriesFn = null;
			//					try {
			//						threadShowList();
			//						hidePb();
			//					} catch (Exception e) {
			//						e.printStackTrace();
			//					}
			//				}
			return null; 
		}
	}
	/**
	 * 러너블. 일기를 비활성화한다
	 */
	class RunnableUpdateDeactivateDiary implements Runnable {		
		public void run(){
			new backgroundThreadUpdateDeactivateDiary().execute();
		}
	}
	/**
	 * backgroundThreadUpdateDeactivateDiary
	 * 비동기 스레드  일기를 비활성화한다
	 * @author blue
	 *
	 */
	public class backgroundThreadUpdateDeactivateDiary extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadUpdateDeactivateDiary");
			// 파라미터 세팅
			PushChatDiary pushChatDiaryParam = new PushChatDiary();

			if(screenMode == 1 || screenMode == 3){
				pushChatDiaryParam.setIdPushChatDiary(pushChatDiaryEntriesFn.get(cancelPosition).getIdPushChatDiary());
				pushChatDiaryParam.setMemberId(pushChatDiaryEntriesFn.get(cancelPosition).getMemberId());
			}else if(screenMode == 2 || screenMode == 4){
				pushChatDiaryParam.setIdPushChatDiary(pushChatMyDiaryEntriesFn.get(cancelPosition).getIdPushChatDiary());
				pushChatDiaryParam.setMemberId(pushChatMyDiaryEntriesFn.get(cancelPosition).getMemberId());
			}

			// 서버 메소드 호출
			if(FragmentHome.restCallCntUp()){
				showPb();
				if(!isFinished){
					callResult = pushChatRest.RestUpdateDeactivateDiary(pushChatDiaryParam);
					FragmentHome.restCallCntDown();
					// 결과 처리
					if(callResult.equals("SUCCESS")){
						needScroll = true;
						// 성공 > 알림창 띄우고 모드에 따라서 목록 재조회.
						if(screenMode == 1 || screenMode == 3){
							handler.sendEmptyMessage(SELECT_SEARCH_DIARY_LIST);
						}else if(screenMode == 2 || screenMode == 4){
							handler.sendEmptyMessage(SELECT_MY_DIARY_LIST);
						}
						showResultDialog(getResources().getString(R.string.delete_success));
					}else{
						// 실패 > 알림창
						showResultDialog(getResources().getString(R.string.delete_fail));
					}
				}
				hidePb();		// @@ 
			}
			countOne = true;		// 다시 호출 되도록 수정..	
			return null; 
		}
	}


	////////////////////////	onActivityResult	///////////////////////////////////////////////////////////////////////

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bundle extraBundle;
		if( requestCode == 5001 ) {
			if(resultCode == Activity.RESULT_OK){		// 정상 반환시.
				Log.d(TAG,"RESULT_OK");
				//				Log.d(TAG,"onActivityResult//5001");
				extraBundle = data.getExtras();		// 번들을 반환했으니까 번들을 불러오면 세팅된 값을 가지고 있음.

				pushChatMemberParam = new PushChatMember();
				String searchMemberId = extraBundle.getString("searchMemberId");	 				// 상호명 검색시 파라미터
				String searchNickName = extraBundle.getString("searchNickName");	 			// 업종 선택시 파라미터
				String searchGender = extraBundle.getString("searchGender");	 			// 업종 선택시 파라미터
				String searchAge = extraBundle.getString("searchAge");	 			// 업종 선택시 파라미터
				String searchPersonalityType = extraBundle.getString("searchPersonalityType");	 			// 업종 선택시 파라미터
				Log.d(TAG,"searchMemberId:"+searchMemberId);		
				Log.d(TAG,"searchNickName:"+searchNickName);
				Log.d(TAG,"searchGender:"+searchGender);
				Log.d(TAG,"searchAge:"+searchAge);
				Log.d(TAG,"searchPersonalityType:"+searchPersonalityType);
				pushChatMemberParam.setMemberId(searchMemberId);
				pushChatMemberParam.setNickName(searchNickName);
				pushChatMemberParam.setGender(searchGender);
				pushChatMemberParam.setAge(searchAge);
				pushChatMemberParam.setPersonalityType(searchPersonalityType);

				// 검색 실행..
				//					handler.sendEmptyMessage(SELECT_SEARCH_MEMBER_LIST);
			}else if(resultCode == Activity.RESULT_CANCELED){
				Log.d(TAG,"RESULT_CANCELED");
			}
		}
	}


	///////////////////////	///////////////////////////////////////////////////////////////////////

	// 이미지 처리
	/**
	 * LoadImage
	 *  이미지 URL 에서 이미지 받아온 스트림을 비트맵으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return bm
	 */
	private Bitmap LoadImage( String $imagePath ) {
		InputStream inputStream = OpenHttpConnection( $imagePath ) ;
		Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;
		return bm;
	}
	/**
	 * OpenHttpConnection
	 *  이미지 URL 에서 이미지 받아와서 스트림으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return stream
	 */
	private InputStream OpenHttpConnection(String $imagePath) {
		// TODO Auto-generated method stub
		InputStream stream = null ;
		try {
			URL url = new URL( $imagePath ) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setRequestMethod( "GET" ) ;
			urlConnection.connect() ;
			if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {
				stream = urlConnection.getInputStream() ;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.d(TAG,"OpenHttpConnection-"+$imagePath);
			Log.w(TAG,"MalformedURLException");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"IOException");
		}
		return stream ;
	}

	////////////////////////	Util	///////////////////////////////////////////////////////////////////////	

	/**
	 * returnThis
	 *  컨택스트 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context returnThis(){
		return getActivity();
	}

	/*
	 * 핸들러를 통한 작업.
	 */
	/**
	 * showMsg
	 *  화면에 토스트 띄움 msg 변수에 내용을 넣어서 호출하면 화면에 토스트를 띄운다.
	 *
	 * @param msg
	 * @param
	 * @return
	 */
	public void showMsg(final String msg){		
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){	 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showToast", 1);
					b.putString("msg", msg);
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	} 

	/**
	 * showResultDialog
	 *  얼럿 띄운다
	 *
	 * @param msg
	 * @param
	 * @return 
	 */
	public void showResultDialog(final String msg){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){	 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showAlert", 1);
					b.putString("msg", msg);			// 화면에 보여줄 메시지
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}
	// 확인을 받는 컨펌 창을 띄운다
	/**
	 * showConfirmDialog
	 *  확인을 받는 컨펌 창을 띄운다
	 *
	 * @param showConfirmCode
	 * @param msg
	 * @return 
	 */
	public void showConfirmDialog(final int showConfirmCode, final String msg){
		if(getActivity()!=null){
			getActivity().runOnUiThread(new Runnable(){		 
				@Override
				public void run(){
					Message message = handler.obtainMessage();				
					Bundle b = new Bundle();
					b.putInt("showConfirm", showConfirmCode);		 
					b.putString("msg", msg);			// 화면에 보여줄 메시지
					message.setData(b);
					handler.sendMessage(message);
				}
			});
		}
	}

	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}

	/**
	 * onResume
	 *  액티비티 리쥼시 닫기 카운터초기화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onResume(){
		super.onResume();
		isFinished = false;
		FragmentHome.app_end = 0;

		//			if(countOne){
		//				countOne = false;		
		//				handler.sendEmptyMessage(SELECT_SEARCH_DIARY_LIST);		// 전체 일기 목록 불러오기 
		//			}else{
		//				Log.d(TAG,"already running..");		 
		//			}

		Log.d(TAG,"onResume/ screenMode:"+screenMode);
		// screenMode 1 : 전체 일기 목록. 2 : 내일기 목록. 3 전체일기 목록 refresh필요. 4. 내일기목록. refresh 필요
		if(screenMode==3){
			handler.sendEmptyMessage(SELECT_SEARCH_DIARY_LIST);
		}else if(screenMode==4){
			handler.sendEmptyMessage(SELECT_MY_DIARY_LIST);
		}


	}
	@Override
	public void onDestroy(){
		isFinished = true;
		super.onDestroy();
	}

}
